<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="分类" prop="pid">
        <el-select v-model="queryParams.pid" placeholder="请选择分类" clearable>
          <el-option
            v-for="dict in typeDict"
            :key="dict.id"
            :label="dict.title"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      border
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="title" />
      <el-table-column label="图片" align="center" prop="url">
        <template slot-scope="scope">
          <image-preview :src="scope.row.url" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" prop="pid">
        <template slot-scope="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['api:goods:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['api:goods:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        style="font-size: 32px"
      >
        <el-form-item label="分类" prop="pid">
          <!-- <el-select v-model="form.pid" placeholder="请选择分类" disabled>
            <el-option
              v-for="dict in typeDict"
              :key="dict.id"
              :label="dict.title"
              :value="dict.id"
            ></el-option>
          </el-select> -->
          {{
            typeDict.find((i) => i.id == form.pid)
              ? typeDict.find((i) => i.id == form.pid).title
              : ""
          }}
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <!-- <el-input v-model="form.title" placeholder="请输入标题" disabled />\ -->
          {{ form.title }}
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <image-preview :src="form.url" :width="100" :height="100" />
        </el-form-item>

        <el-divider content-position="center">零售用户规格信息</el-divider>

        <el-table
          :data="ggList"
          :row-class-name="rowDengjiIndex"
          @selection-change="handleGgSelectionChange"
          border
          ref="dengji"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="100"
          />
          <el-table-column label="商品规格" prop="name" align="center">
          </el-table-column>

          <el-table-column label="商品库存" prop="store" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.store" placeholder="请输入库存" />
            </template>
          </el-table-column>
        </el-table>
        <el-divider content-position="center">代理用户规格信息</el-divider>
        <el-button @click="handleClick" type="primary" style="margin-bottom: 20px;"> 同步库存信息</el-button>

        <el-table
          border
          v-loading="loading"
          :data="form.goodsAgentList"
          style="width: 100%"
          ref="table"
        >
          <el-table-column label="用户等级" align="center" prop="userVip">
          </el-table-column>
          <el-table-column label="规格名称" align="center" prop="name">
          </el-table-column>
          <!-- <el-table-column label="规格价格" align="center" prop="price">
          </el-table-column> -->
          <el-table-column label="商品库存" prop="store" align="center">
            <template slot-scope="scope">
              <el-input-number
                :min="0"
                v-model="scope.row.store"
                placeholder="请输入库存"
              />
            </template>
          </el-table-column>
          <!-- 
          <el-table-column label="预警库存" prop="store" align="center">
            <template slot-scope="scope">
              <el-input-number
                :min="0"
                v-model="scope.row.warnStore"
                placeholder="请输入库存"
              />
            </template>
          </el-table-column> -->
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  listVip,
  listCate,
} from "@/api/api/goods";

import { dictList } from "@/api/api/cate";

export default {
  name: "Goods",
  dicts: ["user_vip"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedDengji: [],
      checkedgg: [],
      cateList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      // 等级价格表格数据
      dengjiList: [],
      ggList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pid: null,
        title: null,
      },
      // 表单参数
      form: {},
      yhList: [],
      // 表单校验
      rules: {},
      typeDict: [],
    };
  },
  created() {
    this.getList();
    this.getYhList();
    this.getFlList();
    dictList().then((res) => {
      this.typeDict = res.data;
    });
  },
  methods: {
    getFlList() {
      this.loading = true;
      // listCate(this.queryParams).then((response) => {
      //   this.cateList = response.rows;
      // });
    },
    changeYh(val) {
      val.userId = this.yhList.find((i) => i.userVip == val.title).id;
    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.status = 1;
      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取用户等级
    getYhList() {
      listVip().then((res) => {
        console.log(res, "asdasdasda");
        this.yhList = res.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        title: null,
        url: null,
        orderNum: null,
        price: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        text: [],
        status: 1,
      };
      this.dengjiList = [];
      this.ggList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.goodsAgentList = [];
      console.log(this.yhList, "this.yhList");
      this.yhList.forEach((element) => {
        let params = {
          userVipId: element.id,
          userVip: element.userVip,
        };

        this.form.goodsAgentList.push(params);
      });
      console.log(this.form.goodsAgentList, "this.form.goodsAgentList");
      this.title = "添加商品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getGoods(id).then((response) => {
        this.form = response.data;
        // this.form.text1 = JSON.parse(this.form.text1);
        // let arr = this.findMissingUserVip(this.form.text1, this.yhList);
        // if (arr.length > 0) {
        //   arr.forEach((i) => {
        //     this.form.text1.push(i);
        //   });
        // }
        this.form.goodsAgentList = this.updateUserList(
          this.form.goodsAgentList,
          this.yhList
        );
        this.dengjiList = response.data.dengjiList;
        this.ggList = response.data.goodsinfoList;
        this.open = true;
        this.title = "修改库存";
      });
    },

    updateUserList(user, yhList) {
      // 1. 将user数组中缺少的数据添加进去
      yhList.forEach((item) => {
        if (!user.some((u) => u.userVip === item.userVip)) {
          user.push({ userVip: item.userVip, price: "", name: "", remark: "" });
        }
      });

      // 2. 删除user数组中多余的数据
      user = user.filter((u) =>
        yhList.some((item) => item.userVip === u.userVip)
      );

      return user;
    },

    handleClick() {
      let storeMap = {};

      this.form.goodsAgentList.forEach((item) => {
        if (item.store !== "") {
          storeMap[item.name] = item.store;
        }
      });

      this.form.goodsAgentList.forEach((item) => {
        if (item.store === "" && storeMap[item.name]) {
          item.store = storeMap[item.name];
        }
      });

      this.form.goodsAgentList.forEach((item) => {
        this.form.goodsAgentList
          .filter(
            (ele) => ele.name === item.name && ele.userVip !== item.userVip
          )
          .forEach((ele) => (ele.store = item.store));
      });
    },

    removeMissingUserVip(array1, array2) {
      const userVipSet = new Set(array1.map((item) => item.userVip));
      const filteredArray2 = array2.filter((item) =>
        userVipSet.has(item.userVip)
      );
      return filteredArray2;
    },

    findMissingUserVip(array1, array2) {
      const missingUserVip = array2.filter(
        (item2) => !array1.some((item1) => item1.userVip === item2.userVip)
      );
      return missingUserVip;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.dengjiList = this.dengjiList;
          this.form.goodsinfoList = this.ggList;
          // this.form.text1 = JSON.stringify(this.form.text1);
          if (this.form.id != null) {
            updateGoods(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    addGg(val, index) {
      let params = {
        name: "",
        price: "",
        userVip: val.userVip,
        userVipId: val.userVipId,
        remark: "1",
        id: "",
        store: "",
        warnStore: 0,
      };
      console.log(params, "params1111");
      this.form.goodsAgentList.splice(index + 1, 0, params);
      // 设置新增数据的用户等级字段
      // 重新渲染表格，以确保合并后的单元格数据可见
      // this.$nextTick(() => {
      //   this.$refs.table.doLayout();
      // });
    },
    deleteGg(row, index) {
      this.form.goodsAgentList.splice(index, 1);
    },

    mergeCells({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (
          rowIndex > 0 &&
          row.userVip === this.form.goodsAgentList[rowIndex - 1].userVip
        ) {
          return {
            rowspan: 0,
            colspan: 0,
            userVip: this.form.goodsAgentList[rowIndex - 1].userVip,
          };
        }
        let count = 1;
        for (let i = rowIndex + 1; i < this.form.goodsAgentList.length; i++) {
          if (row.userVip === this.form.goodsAgentList[i].userVip) {
            count++;
          } else {
            break;
          }
        }
        return {
          rowspan: count,
          colspan: 1,
        };
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delGoods(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 等级价格序号 */
    rowDengjiIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 等级价格添加按钮操作 */
    handleAddDengji() {
      let obj = {};
      obj.title = "";
      obj.price = "";
      this.dengjiList.push(obj);
    },
    handleAddgg() {
      let obj = {};
      obj.name = "";
      obj.price = "";
      this.ggList.push(obj);
    },
    /** 等级价格删除按钮操作 */
    handleDeleteDengji() {
      if (this.checkedDengji.length == 0) {
        this.$modal.msgError("请先选择要删除的等级价格数据");
      } else {
        const dengjiList = this.dengjiList;
        const checkedDengji = this.checkedDengji;
        this.dengjiList = dengjiList.filter(function (item) {
          return checkedDengji.indexOf(item.index) == -1;
        });
      }
    },

    handleDeleteGg() {
      if (this.checkedgg.length == 0) {
        this.$modal.msgError("请先选择要删除的等级价格数据");
      } else {
        const ggList = this.ggList;
        const checkedgg = this.checkedgg;
        this.ggList = ggList.filter(function (item) {
          return checkedgg.indexOf(item.index) == -1;
        });
      }
    },

    /** 复选框选中数据 */
    handleDengjiSelectionChange(selection) {
      this.checkedDengji = selection.map((item) => item.index);
    },

    handleGgSelectionChange(selection) {
      this.checkedgg = selection.map((item) => item.index);
    },

    handleDeleteDengji() {
      if (this.checkedDengji.length == 0) {
        this.$modal.msgError("请先选择要删除的等级价格数据");
      } else {
        const dengjiList = this.dengjiList;
        const checkedDengji = this.checkedDengji;
        this.dengjiList = dengjiList.filter(function (item) {
          return checkedDengji.indexOf(item.index) == -1;
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "api/goods/export",
        {
          ...this.queryParams,
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    },
    rowClassName({ row, rowIndex }) {
      console.log(row, "111111");
      return row.alarm === 1 ? "alarm-row" : "";
    },
  },
};
</script>
<style>
.alarm-row {
  background-color: #f56c6c !important;
}
</style>
